﻿using System;
using System.Collections;
using System.IO;
using System.Text;

namespace Ultima.Xna.Data
{
    public static class StringList
    {
        private static Hashtable _table;
        private static StringEntry[] _entries;
        private static string _language;
        private static byte[] _buffer = new byte[1024];

        public static StringEntry[] Entries { get { return _entries; } }
        public static Hashtable Table { get { return _table; } }
        public static string Language { get { return _language; } }

        public static void LoadStringList(string language)
        {
            _language = language;
            _table = new Hashtable();

            string path = FileManager.GetFilePath(String.Format("cliloc.{0}", language));

            if (path == null)
            {
                _entries = new StringEntry[0];
                return;
            }

            ArrayList list = new ArrayList();

            using (BinaryReader bin = new BinaryReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                bin.ReadInt32();
                bin.ReadInt16();

                while (bin.BaseStream.Length != bin.BaseStream.Position)
                {
                    int number = bin.ReadInt32();
                    bin.ReadByte();
                    int length = bin.ReadInt16();

                    if (length > _buffer.Length)
                        _buffer = new byte[(length + 1023) & ~1023];

                    bin.Read(_buffer, 0, length);
                    string text = Encoding.UTF8.GetString(_buffer, 0, length);

                    list.Add(new StringEntry(number, text));
                    _table[number] = text;
                }
            }

            _entries = (StringEntry[])list.ToArray(typeof(StringEntry));
        }
    }

    public class StringEntry
    {
        private int _number;
        private string _text;

        public int Number { get { return _number; } }
        public string Text { get { return _text; } }

        public StringEntry(int number, string text)
        {
            _number = number;
            _text = text;
        }
    }
}